package com.example.administrator.shzs.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.parse.ParseIndexXrecycleView;
import com.example.administrator.shzs.parse.ParseSearchRecycleview;
import com.example.administrator.shzs.activity.BaseActivity;
import com.example.administrator.shzs.adapter.HomeShopListAdapter;
import com.example.administrator.shzs.adapter.SearchRecycleviewAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.entity.MerchantData;
import com.example.administrator.shzs.entity.mSoRecycleview;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 中间分类菜单
 */

public class CategoryActivity extends BaseActivity {
    //标题
    private String title;
    private TextView tvTitle;
    private LinearLayout One, Two, Three;
    private ImageView buildimage;

    private TextView SortOneO, SortTwoO, SortThreeO;
    private ImageView Back, imageViewSoSo;
    private Context context = this;

    //    下拉菜单
    private PopupWindow mPopupWindow;
    private RecyclerView Index_Soso_RecycleView;
    private List<mSoRecycleview> datalist;
    private SearchRecycleviewAdapter mSoAdapter;
    //下拉菜单中间
    private LinearLayout mPopTwo;
    private TextView pop;
    private TextView InTime;
    private TextView grade;
    private TextView Distance;
    //    中间分类
    private String SortNum = "SortNum";

    //    搜索页面数据
    private XRecyclerView mmSoRecycleview;
    private HomeShopListAdapter IRecyclviewAdapter;
    private List<MerchantData.ListBean> datalistX; //默认加载
    private List<MerchantData.ListBean> datalistXo;//更多加载
    //翻页
    private int page = 1;
    //分类id
    private String SortID;

    //是否点击，
    private boolean isClick = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cate_gory);
        MyApplication.app.activityList.add(this);
        //初始化id
        setViews();
        //获取标题
        final Intent intent = getIntent();
        title = intent.getStringExtra("name");
        SortID = intent.getStringExtra("sortid");

        //设置界面标题
        setMyTitle(title);
        SortOneO.setText(title);
        //从网络获取数据  默认加载页面
        iniDataFromWebMr(1, "SortNum");

        mmSoRecycleview.setLayoutManager(new LinearLayoutManager(context));
        mmSoRecycleview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                iniDataFromWebMr(1, "SortNum");
            }

            @Override
            public void onLoadMore() {
                page++;
                iniDataFromWebMr(page, "SortNum");
            }
        });
//        //点击事件
        inEven();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    mmSoRecycleview.loadMoreComplete();
                    mmSoRecycleview.refreshComplete();

                    break;
                case 1:

                    mSoAdapter = new SearchRecycleviewAdapter(datalist, context);
                    Index_Soso_RecycleView.setAdapter(mSoAdapter);

                    mSoAdapter.setSoSoItem(new SearchRecycleviewAdapter.SoSoItem() {
                        @Override
                        public void Onclick(View view, int postion) {
                            isClick = true;

                            SortOneO.setText(datalist.get(postion).getSortName());
                            tvTitle.setText(datalist.get(postion).getSortName());
                            SortID = datalist.get(postion).getSortID();

                            mPopupWindow.dismiss();
                            iniDataFromWebMr(1, SortNum);
                        }
                    });


                    break;
                case 2:
//                    默认第一次加载数据
                    mmSoRecycleview.setVisibility(View.VISIBLE);
                    buildimage.setVisibility(View.GONE);
                    IRecyclviewAdapter = new HomeShopListAdapter(context, datalistX);
                    mmSoRecycleview.setAdapter(IRecyclviewAdapter);
                    IRecyclviewAdapter.setOnItemClickListener(new HomeShopListAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(MerchantData.ListBean merchantData) {
                            Intent intent = new Intent(CategoryActivity.this, ShopActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("MerchantData", merchantData);
                            intent.putExtras(bundle);

                            startActivity(intent);
                        }

                        @Override
                        public void onShopPayClick(MerchantData.ListBean merchantData) {

                            Intent offlinePay = new Intent(CategoryActivity.this, OfflinePayActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("merchantdata", merchantData);
                            offlinePay.putExtras(bundle);
                            startActivity(offlinePay);

                        }
                    });
                    mmSoRecycleview.refreshComplete();
                    break;
                case 3:
//                    加载更多数据
                    datalistX.addAll(datalistXo);
                    IRecyclviewAdapter.notifyDataSetChanged();
                    datalistXo.clear();
                    mmSoRecycleview.loadMoreComplete();
                    break;
                case 4:
//                   点击分类 没有内容
                    mmSoRecycleview.setVisibility(View.GONE);
                    buildimage.setVisibility(View.VISIBLE);

                    break;
            }
        }
    };


    /**
     * 纬度
     */
    private double latitude;

    /**
     * 经度
     */
    private double longitude;

    /**
     * //从网络获取数据 _  默认加载页面
     */
    private void iniDataFromWebMr(final int page, final String sortName) {

        latitude = MyApplication.app.getLatitude();
        longitude = MyApplication.app.getLongitude();


        String url = Contents.INDEX_XRECYCLE + "?pagesize=20&languageType=2&shoptype=" + SortID
                + "&types=1&pageindex=" + page + "&sortname=" + sortName + "&sortflag=1&lat=" +
                latitude + "&lng=" + longitude;
        Request request = new Request.Builder().url(url).build();
        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String request = response.body().string();

                if (!isClick) {
                    if (page == 1) {

                        try {
                            datalistX = ParseIndexXrecycleView.getIndexXrecyclView(request);

                            if (datalistX.size() > 0) {
                                handler.sendEmptyMessage(2);
                            } else {
                                handler.sendEmptyMessage(4);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } else {

                        try {
                            datalistXo = ParseIndexXrecycleView.getIndexXrecyclView(request);

                            if (datalistX.size() > 0) {
                                handler.sendEmptyMessage(2);
                            } else {
                                handler.sendEmptyMessage(4);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                } else {
                    isClick = false;

                    try {
                        datalistX = ParseIndexXrecycleView.getIndexXrecyclView(request);
                        if (datalistX.size() > 0) {
                            handler.sendEmptyMessage(2);
                        } else {
                            iniDataFromWebMr(1, SortNum);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }

            }
        });
    }


    /**
     * 从网上获取第一个下拉菜单列表数据
     */
    private void iniDataFromWeb() {
        datalist = new ArrayList<>();
        Request request = new Request.Builder().url(Contents.INDEX_CTENTENT).build();
        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String request = response.body().string();
                datalist = ParseSearchRecycleview.getmSoRecycleview(request);
                if (datalist.size() > 0) {
                    handler.sendEmptyMessage(1);
                } else {
                    handler.sendEmptyMessage(0);
                }
            }
        });
    }

    private void showPopupWindow() {

        View contentview = LayoutInflater.from(context).
                inflate(R.layout.activity_category_item, null);
        mPopupWindow = new PopupWindow(contentview);
        Index_Soso_RecycleView = (RecyclerView) contentview.findViewById(R.id.Index_Soso_RecycleView);
        mPopTwo = (LinearLayout) contentview.findViewById(R.id.Two);
        pop = (TextView) contentview.findViewById(R.id.pop);
        InTime = (TextView) contentview.findViewById(R.id.InTime);
        grade = (TextView) contentview.findViewById(R.id.grade);
        Distance = (TextView) contentview.findViewById(R.id.Distance);

        mPopupWindow.setContentView(contentview);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);


        //布局管理器
        Index_Soso_RecycleView.setLayoutManager(new LinearLayoutManager(context));
        mPopupWindow.showAsDropDown(One);


    }

    /**
     * 点击事件
     */
    private void inEven() {

        /*One.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                下拉菜单 第一列
                showPopupWindow();
                mPopTwo.setVisibility(View.GONE);
//                从网络获取数据
                iniDataFromWeb();
            }
        });*/
        Two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                下拉菜单 第一列
                showPopupWindow();
                Index_Soso_RecycleView.setVisibility(View.GONE);
                mPopTwo.setVisibility(View.VISIBLE);


                pop.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SortTwoO.setText(pop.getText().toString());
                        isClick = true;
                        SortNum = "pop";
                        iniDataFromWebMr(1, SortNum);
                        mPopupWindow.dismiss();
                    }
                });

                InTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SortTwoO.setText(InTime.getText().toString());
                        isClick = true;
                        SortNum = "InTime";
                        iniDataFromWebMr(1, SortNum);
                        mPopupWindow.dismiss();
                    }
                });
                grade.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SortTwoO.setText(grade.getText().toString());
                        isClick = true;
                        SortNum = "grade";
                        iniDataFromWebMr(1, "grade");
                        mPopupWindow.dismiss();
                    }
                });
                Distance.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SortTwoO.setText(Distance.getText().toString());
                        isClick = true;
                        SortNum = "Distance";
                        iniDataFromWebMr(1, SortNum);
                        mPopupWindow.dismiss();
                    }
                });


            }
        });

/*
        Three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                下拉菜单 第一列
                showPopupWindow();
//                从网络获取数据
                iniDataFromWeb();
            }
        });*/

        Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        imageViewSoSo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intents = new Intent(CategoryActivity.this,SearchActivity.class);
                startActivity(intents);
            }
        });

    }


    /**
     * 设置界面标题
     *
     * @param title
     */
    private void setMyTitle(String title) {
        if (title != null) {
            tvTitle.setText(title);
        }
    }

    /**
     * 初始化控件
     */
    private void setViews() {
        tvTitle = (TextView) findViewById(R.id.tv_title_categoryactivity);
        mmSoRecycleview = (XRecyclerView) findViewById(R.id.mmSoRecycleview);
        Back = (ImageView) findViewById(R.id.back);
        imageViewSoSo = (ImageView) findViewById(R.id.imageViewSoSo);
        One = (LinearLayout) findViewById(R.id.Onee);
        Two = (LinearLayout) findViewById(R.id.Twoo);
        Three = (LinearLayout) findViewById(R.id.Three);
        SortOneO = (TextView) findViewById(R.id.SortOneO);
        SortTwoO = (TextView) findViewById(R.id.SortTwoO);
        SortThreeO = (TextView) findViewById(R.id.SortThreeO);
        buildimage = (ImageView) findViewById(R.id.buildimage);
//        SortOne = (ImageView) findViewById(R.id.SortOne);
//        SortTwo = (ImageView) findViewById(R.id.SortOne);
//        SortThree = (ImageView) findViewById(R.id.SortOne);
    }


}
